package cn.lili.modules.auth.serviceimpl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.auth.service.OperationQrCodeLoginService;
import cn.lili.modules.member.client.UserClient;
import cn.lili.modules.member.entity.dos.User;
import cn.lili.modules.operationcenter.client.OperationCenterClient;
import cn.lili.modules.operationcenter.entity.dos.OperationCenter;
import cn.lili.modules.operationcenter.entity.vos.ScanCodeModalVO;
import cn.lili.modules.token.TokenGenerate;
import com.alibaba.fastjson.JSON;
import com.pojos.OpenAppUser;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RequiredArgsConstructor
public class OperationQrCodeLoginServiceImpl implements OperationQrCodeLoginService {

    private final UserClient userClient;

    @Value("${fw.appid}")
    String appId;
    @Value("${fw.server}")
    String fwServer;

    private final TokenGenerate tokenGenerate;
    private final OperationCenterClient operationCenterClient;

    /**
     * 创建二维码
     *
     * @param scene  应用场景
     * @param userId 扫码绑定时的用户
     * @return 二维码图片
     */
    @SneakyThrows
    @Override
    public ResultMessage<Object> createQrCode(String scene, String userId) {
        HttpRequest codeExpireHttp = HttpUtil.createGet(fwServer + "/createQrcode?appId=" + appId + "&scene=" + scene + "&userId=" + userId);

        JSONObject codeExpireJson = new JSONObject(codeExpireHttp.execute().body());
        if (codeExpireJson.getInt("code") != 200) {
            return ResultUtil.error(codeExpireJson.getInt("code"), String.valueOf(codeExpireJson.get("msg")));
        }
        return ResultUtil.data(codeExpireJson.get("data"));
    }


    /**
     * 校验code的接口
     * @param code
     * @return
     */
    @Override
    public ResultMessage<Object> checkCode(String code) {
        // 1.调用scan_code服务的checkCode接口获取用户信息
        JSONObject codeJson;
        try {
            log.info("#checkCode# 开始请求===");
            HttpRequest codeHttp = HttpUtil.createGet(fwServer + "/checkCode?code=" + code);
//            String body = codeHttp.execute().body();
//            log.info("checkCode --- ： {}", body);
            codeJson = new JSONObject(codeHttp.execute().body());
            log.info("#checkCode# --- 扫码登录验证结果： {}", codeJson);
        } catch (Exception e) {
            log.info("#checkCode# 检查二维码异常,异常信息: ", e);
            throw new ServiceException("服务器异常");
        }
        // 2.根据获取到的用户信息的openid确认商户是否有绑定此openId的
        if (codeJson.getInt("code") != 200) {
            return ResultUtil.error(codeJson.getInt("code"), codeJson.getStr("msg"));
        }
        JSONObject entries = (JSONObject) codeJson.get("data");
        ScanCodeModalVO scanCodeModal = com.alibaba.fastjson.JSONObject.toJavaObject(JSON.parseObject(entries.toString()), ScanCodeModalVO.class);

        if (scanCodeModal == null) {
            return ResultUtil.error(500, "未获取到扫码信息");
        }
        log.info("#checkCode# scanCodeModal:{}", com.alibaba.fastjson.JSONObject.toJSONString(scanCodeModal));

        // 4.如果没有，则将此openid绑定到当前用户token对应的商户
        if (StringUtils.isNotEmpty(scanCodeModal.getUserId())) {
            OpenAppUser openAppUser = scanCodeModal.getOpenAppUser();
            log.info("openAppUser = {}", openAppUser);
            String scene = scanCodeModal.getScene();
            User user = userClient.getByOpenId(openAppUser.getOpenId(), scene);
            if (user != null && StringUtils.isNotEmpty(user.getId())) {
                return ResultUtil.error(500, "该飞语在此场景下已存在账号，不允许进行绑定");
            }
            userClient.updateFyById(openAppUser.getOpenId(), openAppUser.getAccount(), openAppUser.getNickName(), scanCodeModal.getUserId(), scene);
            return ResultUtil.data("绑定成功");
        }
        // 3.如果有，则是登录逻辑，返回用户token
        if (scanCodeModal.getOpenAppUser() != null && scanCodeModal.getOpenAppUser().getOpenId() != null && scanCodeModal.getScene() != null) {
            OpenAppUser openAppUser = scanCodeModal.getOpenAppUser();
            String openId = openAppUser.getOpenId();
            String scene = scanCodeModal.getScene();
            User user = userClient.getByOpenId(openId, scene);
            if (user == null || StringUtils.isEmpty(user.getId())) {
                return ResultUtil.error(500, "未绑定飞语");
            }
            //查询运营中心账号
            OperationCenter operationCenter = operationCenterClient.getOperationCenter(user.getId());
            if (operationCenter == null) {
                return ResultUtil.error(500, "未找到相关运营中心账号信息");
            }
            return ResultUtil.data(tokenGenerate.generateToken(user, false));
        }
        // 5.如果用户是未登录状态，则直接返回报错，提示此飞语账号未绑定商城用户
        return ResultUtil.error(500, "未登录且未绑定飞语");
    }
}
